import React, { useState, useEffect } from "react"
import axios from "axios"
import { MD5 } from "crypto-js";

import "./register.css"
import { Input, Toast } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import { Notify } from "react-vant";

function Register() {
    // 用户名密码注册
    const navigate = useNavigate();
    const [form, setForm] = useState({
        username: "",
        password: "",
        phone: ""
    })


    const [isshow, setIsshow] = useState("用户名密码注册")


    const [phone, setPhone] = useState('');
    const [code, setCode] = useState('');
    const [countdown, setCountdown] = useState(0);
    const [isAgreed, setIsAgreed] = useState(false);
    const [phoneError, setPhoneError] = useState('');

    useEffect(() => {
        if (countdown > 0) {
            const timer = setTimeout(() => {
                setCountdown(countdown - 1);
            }, 1000);
            return () => clearTimeout(timer);
        }
    }, [countdown]);


    const validatePhone = (phoneNumber) => {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phoneNumber);
    };

    const handleSendCode =async () => {
        if (!phone) {
            setPhoneError('请输入手机号');
            return;
        }

        if (!validatePhone(phone)) {
            setPhoneError('请输入正确的手机号');
            return;
        }
        

        try {
            await axios.post('http://localhost:3010/sendSms', { 
                ...form,
                phone:phone 
            });
            // Notify.show({ type: 'success', message: '验证码发送成功' })
            Toast.show({
                content: '验证码发送成功',
                position: 'top',
              })
            // Times();
            setPhoneError('');
            setCountdown(60); // 60秒倒计时
        } catch (error) {
            Toast.show({
                content: '该手机号已注册，请重新输入',
                position: 'top',
              })
            // Notify.show({ type: 'danger', message: '手机号已注册' })
        }

       
        // 在实际应用中，这里应有发送验证码的API调用

       


        console.log('发送验证码到:', phone);
    };

    const handleRegister =async () => {
        if (!phone) {
            setPhoneError('请输入手机号');
            return;
        }

        if (!validatePhone(phone)) {
            setPhoneError('请输入正确的手机号');
            return;
        }

        if (!code) {
            alert('请输入验证码');
            return;
        }

        if (!isAgreed) {
            alert('请阅读并同意用户协议和隐私政策');
            return;
        }

        // 在实际应用中，这里应有验证手机号和验证码的API调用
        await axios.post('http://localhost:3010/verify-code', {
            phone:phone,
            code:code
        }).then(res => {
            if (res.data.code === 200) {
                Toast.show({
                    content: '登录成功',
                    position: 'top',
                  })
                navigate("/login")
            } else {
                alert('验证失败')
            }
        })

        
        console.log('注册信息:', { phone, code });
        // navigate('/login');
    };


    return (
        <React.Fragment>

            <div className="ljl-bigbox">
                <div className="ljl-bigbox-top">
                    <div className="ljl-bigbox-top-logo">LOGO</div>
                </div>
                <div className="ljl-bigbox-center">
                    <h4 className="ljl-bigbox-center-font">Hi~</h4>

                    <div>
                        <div className="input-container" >
                            <div className="input-label">手机号码</div>
                            <div className="phone-input-group">
                                <div className="country-code">+86</div>
                                <Input
                                    type="text"
                                    className="phone-input"
                                    placeholder="请输入手机号"
                                    value={phone}
                                    onChange={(e) => {
                                        setPhone(e);
                                        if (phoneError) setPhoneError('');
                                    }}
                                    maxLength={11}
                                />
                            </div>
                            {phoneError && <div className="error-message">{phoneError}</div>}
                        </div>


                        <div className="input-container">
                            <div className="input-label">验证码</div>
                            <div className="code-input-group">
                                <Input
                                    type="text"
                                    className="code-input"
                                    placeholder="请输入验证码"
                                    value={code}
                                    onChange={(e) => setCode(e)}
                                // maxLength={6}
                                />
                                <button
                                    className={`send-code-button ${countdown > 0 ? 'disabled' : ''}`}
                                    onClick={handleSendCode}
                                    disabled={countdown > 0}
                                >
                                    {countdown > 0 ? `重新发送(${countdown}s)` : '获取验证码'}
                                </button>
                            </div>
                        </div>

                        <div style={{ width: "90%", margin: "auto", display: "flex", justifyContent: "right", textAlign: "right" }}>
                            <div className="ljl-regiaterPhone" onClick={() => { navigate("/register") }}>用户名密码注册</div>
                        </div>


                        <div className="agreement-container">
                            <div className="checkbox-wrapper" onClick={() => setIsAgreed(!isAgreed)}>
                                <div className={`checkbox ${isAgreed ? 'checked' : ''}`}>
                                    {isAgreed && (
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="16" height="16">
                                            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z" />
                                        </svg>
                                    )}
                                </div>
                            </div>
                            <div className="agreement-text">
                                我已阅读并同意 <span className="link">《用户协议》</span>和<span className="link">《隐私政策》</span>
                            </div>
                        </div>


                        <button className="register-button" onClick={handleRegister}>
                            注册
                        </button>
                    </div>


                </div>

            </div>

        </React.Fragment>
    )
}

export default Register